import axios from 'axios'
import router from '../router/index';
import {
  getLocalStorage
} from './localStorage'
import {
  message
} from 'ant-design-vue';

let token

export function setToken(t) {
  token = t
}

axios.defaults.withCredentials = true;

axios.interceptors.request.use(config => {
  let backFlag = config.url.indexOf('backend')
  let userInfo = ''
  if (backFlag > 0) {
    userInfo = getLocalStorage('manageToken')
  } else {
    userInfo = getLocalStorage('accessToken')
  }
  let urlFlag = config.url.split('/')[2]
  if (urlFlag != 'pub') {
    let token = ''
    if (userInfo && config.url.indexOf('login') === -1) {
      token = userInfo
    }
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    if (config.url.indexOf('export') > -1) {
      config.responseType = "arraybuffer"
    }
  }
  return config
}, err => {
  return Promise.resolve(err)
})

axios.interceptors.response.use(
  response => {
    if (response.status === 200) {
      if (response.data.code === '999998') {
        message.error(response.message)
        router.push({
          path: '/'
        });
      } else if (response.data.code === '999999') {
        message.error(response.message)
      }
      return Promise.resolve(response)
    } else if (response.status === 415) {
      message.error('请求参数类型错误')
    } else if (response.status === 404) {
      message.error('请求资源未找到')
    } else if (response.status === 500) {
      message.error(response.message)
    } else {
      return Promise.reject(response)
    }
  }
)

/**
 * get方法，对应get请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */

export function get(url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {
      params: params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * put，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function put(url, params) {
  return new Promise((resolve, reject) => {
    axios.put(url, params)
      .then(res => {
        resolve(res)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * delete，对应delete请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function delete_(url, params) {
  return new Promise((resolve, reject) => {
    axios.delete(url, {
      params: params
    }).then(res => {
      resolve(res)
    }).catch(err => {
      reject(err)
    })
  })
}
